<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <el-form-item label="Webhook配置编号" prop="webhookId">
        <el-input v-model="formData.webhookId" placeholder="请输入Webhook配置编号" />
      </el-form-item>
      <el-form-item label="平台编号" prop="platformId">
        <el-input v-model="formData.platformId" placeholder="请输入平台编号" />
      </el-form-item>
      <el-form-item label="店铺编号" prop="storeId">
        <el-input v-model="formData.storeId" placeholder="请输入店铺编号" />
      </el-form-item>
      <el-form-item label="事件ID" prop="eventId">
        <el-input v-model="formData.eventId" placeholder="请输入事件ID" />
      </el-form-item>
      <el-form-item label="事件类型" prop="eventType">
        <el-select v-model="formData.eventType" placeholder="请选择事件类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CROSSBORDER_DATA_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="请求头" prop="requestHeaders">
        <el-input v-model="formData.requestHeaders" placeholder="请输入请求头" />
      </el-form-item>
      <el-form-item label="请求体" prop="requestBody">
        <el-input v-model="formData.requestBody" placeholder="请输入请求体" />
      </el-form-item>
      <el-form-item label="响应状态码" prop="responseStatus">
        <el-input v-model="formData.responseStatus" placeholder="请输入响应状态码" />
      </el-form-item>
      <el-form-item label="响应体" prop="responseBody">
        <el-input v-model="formData.responseBody" placeholder="请输入响应体" />
      </el-form-item>
      <el-form-item label="处理状态" prop="processStatus">
        <el-select v-model="formData.processStatus" placeholder="请选择处理状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_PROCESS_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="处理时间" prop="processTime">
        <el-date-picker
          v-model="formData.processTime"
          type="date"
          value-format="x"
          placeholder="选择处理时间"
        />
      </el-form-item>
      <el-form-item label="处理时长（毫秒）" prop="processDuration">
        <el-input v-model="formData.processDuration" placeholder="请输入处理时长（毫秒）" />
      </el-form-item>
      <el-form-item label="错误信息" prop="errorMsg">
        <el-input v-model="formData.errorMsg" placeholder="请输入错误信息" />
      </el-form-item>
      <el-form-item label="重试次数" prop="retryCount">
        <el-input v-model="formData.retryCount" placeholder="请输入重试次数" />
      </el-form-item>
      <el-form-item label="业务类型" prop="businessType">
        <el-select v-model="formData.businessType" placeholder="请选择业务类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CROSSBORDER_DATA_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务数据ID" prop="businessId">
        <el-input v-model="formData.businessId" placeholder="请输入业务数据ID" />
      </el-form-item>
      <el-form-item label="来源IP" prop="sourceIp">
        <el-input v-model="formData.sourceIp" placeholder="请输入来源IP" />
      </el-form-item>
      <el-form-item label="用户代理" prop="userAgent">
        <el-input v-model="formData.userAgent" placeholder="请输入用户代理" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getStrDictOptions, getBoolDictOptions } from '@/utils/dict'
import { PlatformWebhookLogApi, PlatformWebhookLogVO } from '@/api/crossborder/platformwebhooklog'

/** 跨境电商平台Webhook事件日志 表单 */
defineOptions({ name: 'PlatformWebhookLogForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  webhookId: undefined,
  platformId: undefined,
  storeId: undefined,
  eventId: undefined,
  eventType: undefined,
  requestHeaders: undefined,
  requestBody: undefined,
  responseStatus: undefined,
  responseBody: undefined,
  processStatus: undefined,
  processTime: undefined,
  processDuration: undefined,
  errorMsg: undefined,
  retryCount: undefined,
  businessType: undefined,
  businessId: undefined,
  sourceIp: undefined,
  userAgent: undefined,
})
const formRules = reactive({
  webhookId: [{ required: true, message: 'Webhook配置编号不能为空', trigger: 'blur' }],
  platformId: [{ required: true, message: '平台编号不能为空', trigger: 'blur' }],
  eventType: [{ required: true, message: '事件类型不能为空', trigger: 'change' }],
  processStatus: [{ required: true, message: '处理状态（0待处理 1处理中 2处理成功 3处理失败）不能为空', trigger: 'blur' }],
  retryCount: [{ required: true, message: '重试次数不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PlatformWebhookLogApi.getPlatformWebhookLog(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PlatformWebhookLogVO
    if (formType.value === 'create') {
      await PlatformWebhookLogApi.createPlatformWebhookLog(data)
      message.success(t('common.createSuccess'))
    } else {
      await PlatformWebhookLogApi.updatePlatformWebhookLog(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    webhookId: undefined,
    platformId: undefined,
    storeId: undefined,
    eventId: undefined,
    eventType: undefined,
    requestHeaders: undefined,
    requestBody: undefined,
    responseStatus: undefined,
    responseBody: undefined,
    processStatus: undefined,
    processTime: undefined,
    processDuration: undefined,
    errorMsg: undefined,
    retryCount: undefined,
    businessType: undefined,
    businessId: undefined,
    sourceIp: undefined,
    userAgent: undefined,
  }
  formRef.value?.resetFields()
}
</script>